package com.seamtop.cuber.web.service.impl;

import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.entriy.CuberCounter;
import com.seamtop.cuber.common.entriy.CuberReducer;
import com.seamtop.cuber.common.entriy.ESResult;
import com.seamtop.cuber.common.entriy.ESSearchBean;
import com.seamtop.cuber.core.ESManager;
import com.seamtop.cuber.web.service.ESDataService;
import com.seamtop.cuber.web.util.SearchParamsUtil;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Search;
import org.springframework.stereotype.Service;

/**
 * Created by zongjunfeng on 2015/9/23.
 */

@Service
public class ESDataServiceImpl implements ESDataService {

    public ESResult getCuberData(ESSearchBean esSearchBean) throws Exception{
        JestClient jestClient = ESManager.getClient();
        String res = SearchParamsUtil.combSearchParams(esSearchBean);
        Search search = new Search.Builder(res).addIndex(esSearchBean.getIndex()).addType(esSearchBean.getType()).build();
        JestResult result = jestClient.execute(search);
        ESResult esResult = null;
        if(esSearchBean.getReducerId() != null){
            esResult = SearchParamsUtil.parseSEResult(result.getJsonString());
            String reducerName = esSearchBean.getReducerName();
            CuberReducer cuberReducer = DataObject.getCuberReducerMap().get(reducerName);
            esResult.setTitle(cuberReducer.getDesc());
            esResult.setName(reducerName);
        }else{
            esResult = SearchParamsUtil.parseCounterSEResult(result.getJsonString());
            String counterName = esSearchBean.getCounterName();
            String counterId = esSearchBean.getCounterId();
            CuberCounter cuberCounter = DataObject.getCuberCounterMap().get(counterName);
            esResult.setTitle(cuberCounter.getCounterDesc());
            esResult.setName(counterName);
        }
        return esResult;
    }
}
